package th.retrofit.lib;

import java.util.ArrayList;
import java.util.List;

/**
 * 给定一个单链表，其中的元素按升序排序，将其转换为高度平衡的二叉搜索树。
 *
 * 本题中，一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
 */
public class Solution109 {

    public TreeNode sortedListToBST(ListNode head) {
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        int[] nums = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            nums[i] = list.get(i);
        }
        return sortedListToBST(nums, 0, nums.length - 1);
    }

    public TreeNode sortedListToBST(int[] nums, int start, int end) {
        if (start > end) return null;
        int middle = (start + end) / 2;
        TreeNode cur = new TreeNode(nums[middle]);
        cur.left = sortedListToBST(nums, start, middle - 1);
        cur.right = sortedListToBST(nums, middle + 1, end);
        return cur;
    }

    public TreeNode sortedListToBST1(ListNode head) {
        return sortedListToBST1(head, null);
    }

    public TreeNode sortedListToBST1(ListNode head, ListNode tail) {
        if (head == null || head == tail) {
            return null;
        }
        ListNode slow = head, fast = head;
        while (fast != tail && fast.next != tail) {
            slow = slow.next;
            fast = fast.next.next;
        }
        TreeNode cur = new TreeNode(slow.val);
        cur.left = sortedListToBST1(head, slow);
        cur.right = sortedListToBST1(slow.next, tail);
        return cur;
    }

    public static void main(String[] args) {
        ListNode root = ListNode.arr2Node(-10, -3, 0, 5, 9);
        TreeNode treeNode = new Solution109().sortedListToBST1(root);
        System.out.println(treeNode);
    }

}
